import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';
import JSON5 from 'json5';

import {
  addHarAbility,
  initExecuteCommand,
  runHvigorAsync,
  runHvigorFailAsync,
  runShouldFail
} from '../../common/common';
import { addOhPackageDps } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType, SignType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';
import { getJson5Obj } from "../../../../src/utils/json-util";

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {
    [ModuleTemplateType.SharedLibrary]: 1,
    [ModuleTemplateType.StaticLibrary]: 1
  },
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  // 创建API14+ stage empty工程
  const projectRootPath = project.projectRootPath();
  const harModuleRootPath = project.getModule('staticLibrary').moduleRootPath();
  const hspModuleRootPath = project.getModule('shareLibrary').moduleRootPath();

  // 添加har和hsp模块，在har模块添加Ability
  // har模块module.json5-abilities中添加配置home ability
  await addHarAbility(harModuleRootPath, projectRootPath);
  const harModuleJsonPath = path.resolve(harModuleRootPath, 'src/main/module.json5');
  const moduleJsonObj = getJson5Obj(harModuleJsonPath);
  moduleJsonObj.module.abilities[0].skills =  [
    {
      'entities': [
        'entity.system.home'
      ],
      'actions': [
        'action.system.home'
      ]
    }
  ];
  fse.writeJSONSync(harModuleJsonPath, moduleJsonObj);

  // hsp依赖har模块
  await addOhPackageDps(hspModuleRootPath, {
    'staticLibrary': 'file:../staticLibrary',
  });

  // 点击make module hsp
  const command = ['assembleHsp'];

  const result = await runHvigorFailAsync(projectRootPath, command);
  record.addStep('查看报错信息中是否存在hsp has entry ability', result);
  expect(result.stderr).toContain('hsp has entry ability');
  expect(result.stderr).toContain('BUILD FAILED');
};

TestCaseBuilder.builder()
  .caseName('check_har_uiability_homeAbility')
  .description(
    '创建API14+ stage empty工程；\n' +
    '2 添加har和hsp模块，在har模块添加Ability；\n' +
    '3 har模块module.json5-abilities中添加配置home ability；\n' +
    '4 hsp依赖har模块；\n' +
    '5 点击make module hsp；\n'
  )
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.AR).build())
  .testFun(testFun)
  .load();
